package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.domain.AjaxResult;
import com.itheima.common.domain.PageInfo;
import com.itheima.common.utils.StringUtils;
import com.itheima.common.OrderStatus;
import com.itheima.dto.OmsOrderDto;
import com.itheima.dto.OmsOrderDto2;
import com.itheima.order.entity.OmsOrder;
import com.itheima.order.entity.OmsOrderItem;
import com.itheima.order.entity.OmsOrderOperateHistory;
import com.itheima.service.OmsOrderItemService;
import com.itheima.service.OmsOrderOperateHistoryService;
import com.itheima.service.OmsOrderService;
import com.itheima.vo.OmsMoneyInfoVo;
import com.itheima.vo.OmsOrderDeliveryVo;
import com.itheima.vo.OmsReceiverInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//后台关于订单的修改
@Slf4j
@RestController
@RequestMapping("/order")
public class OmsOrderController {

    @Autowired
    private OmsOrderService omsOrderService;

    @Autowired
    private OmsOrderOperateHistoryService omsOrderOperateHistoryService;

    @Autowired
    private OmsOrderItemService omsOrderItemService;

    /**
     * 批量删除
     *
     * @param ids
     */
    @PostMapping("/delete")
    public void delete(String ids) {
        List<Long> longs = StringUtils.toList(ids);
        omsOrderService.removeByIds(longs);
    }

    /**
     * 查询订单
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(value = "createTime", required = false) String createTime, @RequestParam(value = "orderSn", required = false) String orderSn, @RequestParam(value = "orderType", required = false) Integer orderType, @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "receiverKeyword", required = false) String receiverKeyword, @RequestParam(value = "sourceType", required = false) String sourceType, @RequestParam(value = "status", required = false) String status) {
        Page<OmsOrder> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.like(createTime != null, OmsOrder::getCreateTime, createTime)
                .like(orderSn != null, OmsOrder::getOrderSn, orderSn)
                .eq(orderType != null, OmsOrder::getOrderType, orderType)
                .like(receiverKeyword != null, OmsOrder::getReceiverPhone, receiverKeyword)
                .like(receiverKeyword != null, OmsOrder::getReceiverName, receiverKeyword)
                .eq(sourceType != null, OmsOrder::getSourceType, sourceType)
                .eq(status != null, OmsOrder::getStatus, status);
        omsOrderService.page(page, lqw);
        PageInfo pageInfo = PageInfo.toPageList(page);
        return AjaxResult.success(pageInfo);
    }


    /**
     * 批量关闭订单
     *
     * @param ids
     * @param note
     * @return
     */
    @PostMapping("/update/close")
    public AjaxResult close(@RequestParam("ids") String ids, @RequestParam("note") String note) {
        List<Long> longs = StringUtils.toList(ids);
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.in(OmsOrder::getId, longs)
                .set(OmsOrder::getStatus, OrderStatus.Closed)
                .set(OmsOrder::getNote, note);
        omsOrderService.update(luw);
        return AjaxResult.success();
    }

    /**
     * 批量发货
     *
     * @param deliveryParamList
     * @return
     */
    @PostMapping("/update/delivery")
    public AjaxResult delivery(@RequestBody List<OmsOrderDeliveryVo> deliveryParamList) {
        for (OmsOrderDeliveryVo omsOrderDeliveryVo : deliveryParamList) {
            LambdaUpdateWrapper<OmsOrder> luq = new LambdaUpdateWrapper<>();
            LocalDateTime now = LocalDateTime.now();
            luq.eq(OmsOrder::getId, omsOrderDeliveryVo.getOrderId())
                    .set(OmsOrder::getStatus, OrderStatus.Shipped)
                    .set(omsOrderDeliveryVo.getDeliveryCompany() != null, OmsOrder::getDeliveryCompany, omsOrderDeliveryVo.getDeliveryCompany())
                    .set(omsOrderDeliveryVo.getDeliverySn() != null, OmsOrder::getDeliverySn, omsOrderDeliveryVo.getDeliverySn())
                    .set(OmsOrder::getReceiveTime, now);
            omsOrderService.update(luq);
        }
        return AjaxResult.success();
    }

    /**
     * 修改订单金额
     *
     * @param OmsMoneyInfo
     * @return
     */
    @PostMapping("/update/moneyInfo")
    public AjaxResult moneyInfo(@RequestBody OmsMoneyInfoVo OmsMoneyInfo) {
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(OmsMoneyInfo.getOrderId() != null, OmsOrder::getId, OmsMoneyInfo.getOrderId())
                .set(OmsMoneyInfo.getDiscountAmount() != null, OmsOrder::getDiscountAmount, OmsMoneyInfo.getDiscountAmount())
                .set(OmsMoneyInfo.getFreightAmount() != null, OmsOrder::getFreightAmount, OmsMoneyInfo.getFreightAmount())
                .set(OmsMoneyInfo.getStatus() != null, OmsOrder::getStatus, OmsMoneyInfo.getStatus());
        omsOrderService.update(luw);
        return AjaxResult.success();
    }

    /**
     * 修改备注
     *
     * @param id
     * @param note
     * @param status
     * @return
     */
    @PostMapping("/update/note")
    public AjaxResult note(@RequestParam("id") Long id, @RequestParam("note") String note, @RequestParam("status") Integer status) {
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(id != null, OmsOrder::getId, id)
                .set(note != null, OmsOrder::getNote, note)
                .set(status != null, OmsOrder::getStatus, status);
        omsOrderService.update(luw);
        return AjaxResult.success();
    }

    /**
     * 修改购买用户信息
     *
     * @param omsReceiverInfo
     * @return
     */
    @PostMapping("/update/receiverInfo")
    public AjaxResult receiverInfo(@RequestBody OmsReceiverInfoVo omsReceiverInfo) {
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(omsReceiverInfo.getOrderId() != null, OmsOrder::getId, omsReceiverInfo.getOrderId())
                .set(omsReceiverInfo.getReceiverCity() != null, OmsOrder::getReceiverCity, omsReceiverInfo.getReceiverCity())
                .set(omsReceiverInfo.getReceiverDetailAddress() != null, OmsOrder::getReceiverDetailAddress, omsReceiverInfo.getReceiverDetailAddress())
                .set(omsReceiverInfo.getReceiverName() != null, OmsOrder::getReceiverName, omsReceiverInfo.getReceiverName())
                .set(omsReceiverInfo.getReceiverPhone() != null, OmsOrder::getReceiverPhone, omsReceiverInfo.getReceiverPhone())
                .set(omsReceiverInfo.getReceiverPostCode() != null, OmsOrder::getReceiverPostCode, omsReceiverInfo.getReceiverPostCode())
                .set(omsReceiverInfo.getReceiverProvince() != null, OmsOrder::getReceiverProvince, omsReceiverInfo.getReceiverProvince())
                .set(omsReceiverInfo.getReceiverRegion() != null, OmsOrder::getReceiverRegion, omsReceiverInfo.getReceiverRegion())
                .set(omsReceiverInfo.getStatus() != null, OmsOrder::getStatus, omsReceiverInfo.getStatus());
        omsOrderService.update(luw);
        return AjaxResult.success();
    }

    /**
     * 查询详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable String id) {
        if (id != null) {
            long Lid = Long.parseLong(id);

            //构造器
            LambdaQueryWrapper<OmsOrderItem> lqwOrderItem = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<OmsOrderOperateHistory> lqwHistory = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<OmsOrder> lqwOrder = new LambdaQueryWrapper<>();

            //条件查询
            lqwOrder.eq(OmsOrder::getId, Lid);
            lqwHistory.eq(OmsOrderOperateHistory::getOrderId, Lid);
            lqwOrderItem.eq(OmsOrderItem::getOrderId, Lid);

            //获取结果
            OmsOrder order = omsOrderService.getOne(lqwOrder);
            List<OmsOrderOperateHistory> operateHistory = omsOrderOperateHistoryService.list(lqwHistory);
            List<OmsOrderItem> omsOrderItem = omsOrderItemService.list(lqwOrderItem);

            //创建返回对象
            OmsOrderDto orderDto = new OmsOrderDto();

            //填入值historyList
            Map<String, List<OmsOrderOperateHistory>> history = new HashMap<>();
            history.put("historyList", operateHistory);
            orderDto.setOmsOrderOperateHistoryList(history);

            //填入值orderItemList
            Map<String, List<OmsOrderItem>> itemList = new HashMap<>();
            itemList.put("orderItemList", omsOrderItem);
            orderDto.setOrderItemList(itemList);

            //将order的值复制到orderdto
            BeanUtils.copyProperties(order, orderDto);
            //返回
            return AjaxResult.success(orderDto);
        } else {
            return AjaxResult.error();
        }
    }

    //======================================================================================
    //手机端代码

    /**
     * 用户取消订单
     */
    @PostMapping("/cancelUserOrder")
    public AjaxResult canceUserOrder(@RequestBody String id) {
        long l = Long.parseLong(id);
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(OmsOrder::getId, l).set(OmsOrder::getStatus, OrderStatus.invalid);
        return AjaxResult.success();
    }

    /**
     * 用户确认收货
     *
     * @param id
     * @return
     */
    @PostMapping("/confirmReceiveOrder")
    public AjaxResult confirmReceiveOrder(@RequestBody String id) {
        long l = Long.parseLong(id);
        LambdaUpdateWrapper<OmsOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(OmsOrder::getId, l).set(OmsOrder::getStatus, OrderStatus.Completed);
        return AjaxResult.success();
    }

    //根据id查询订单详情
    @GetMapping("/detail/{orderId}")
    private AjaxResult detailById(@PathVariable Long orderId) {
        LambdaQueryWrapper<OmsOrder> lqwOrder = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OmsOrderItem> lqwOrderItem = new LambdaQueryWrapper<>();

        lqwOrderItem.eq(OmsOrderItem::getOrderId, orderId);
        lqwOrder.eq(OmsOrder::getId, orderId);

        OmsOrder order = omsOrderService.getOne(lqwOrder);
        List<OmsOrderItem> omsOrderItem = omsOrderItemService.list(lqwOrderItem);

        //创建返回对象
        OmsOrderDto2 orderDto = new OmsOrderDto2();

        //填入值orderItemList
        Map<String, List<OmsOrderItem>> itemList = new HashMap<>();
        itemList.put("orderItemList", omsOrderItem);
        orderDto.setOrderItemList(itemList);

        //将order的值复制到orderdto
        BeanUtils.copyProperties(order, orderDto);

        //返回
        return AjaxResult.success(orderDto);
    }


}
